package com.luo.chengrui.framework.sadatapermission.config;

import com.luo.chengrui.framework.sadatapermission.core.aop.DataPermissionContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 多租户 Context Web 过滤器
 * 将请求 Header 中的 permission-code 解析出来，添加到 {@link DataPermissionContextHolder} 中，这样后续的 DB 等操作，可以灵活获取到对应权限子项。
 *
 * @author luodz
 */
public class SaDataPermissionContextWebFilter extends OncePerRequestFilter {

    private static String HEADER_PERMISSION_CODE = "Permission-Code";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 设置

        String permissionSubCode = request.getHeader(HEADER_PERMISSION_CODE);
        if (permissionSubCode != null) {
            DataPermissionContextHolder.setPermissionCode(permissionSubCode);
        }
        try {
            chain.doFilter(request, response);
        } finally {
            // 清理
            DataPermissionContextHolder.clearPermissionCode();
        }
    }

}
